/*
 * $Id$
 */
package corejs.parser;

import corejs.TokenType;

import corejs.expr.Expression;

import corejs.stmt.For;
import corejs.stmt.Statement;

import static corejs.JsTokenType.*;

public class ForParser implements StatementParser {
   
   /**
    *
    * @param parser
    * @return
    */
   @Override
   public Statement statement(final PrattParser parser) {
      parser.nextToken(LEFT_PAREN);      
      
      final Expression init = expr(parser, SEMICOLON);      
      final Expression test = expr(parser, SEMICOLON);
      final Expression step = expr(parser, RIGHT_PAREN);
      
      final Statement loop = 
         parser.match(LEFT_BRACE) ? parser.block(RIGHT_BRACE) : parser.statement();      
      
      return new For(init, test, step, loop);
   }
   
   /**
    *
    * @param parser
    * @param checked
    * @return
    */
   private Expression expr(final PrattParser parser, final TokenType checked) {
      if (parser.match(checked)) {
         return null;
      }
      final Expression expr = parser.expr();
      parser.nextToken(checked);
      return expr;
   }
}
